package org.lc.cmd.impl.bridge;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jline.reader.LineReader;
import org.jline.utils.AttributedString;
import org.lc.cmd.CmdDataBridge;
import org.lc.cmd.impl.TerminalRunner;
import org.springframework.lang.Nullable;

import java.io.IOException;

/**
 * 一体方式的桥
 */
@Slf4j
@AllArgsConstructor
public class OverallBridge implements CmdDataBridge {
    private TerminalRunner terminalRunner;

    @Override
    public void sendCmdLine(String line) {
        try {
            Object result = terminalRunner.getRegistry().execute(line);
            terminalRunner.getResultManager().handleResult(result, line);
        } catch (Exception e) {
            terminalRunner.getResultManager().handleResult(e, line);
        }
    }

    @Override
    public String readLine(String prompt) {
        return terminalRunner.getReader().readLine(prompt);
    }

    @Override
    public void write(AttributedString str, boolean above) {
        LineReader reader = terminalRunner.getReader();
        if (above) {
            reader.printAbove(str);
        } else {
            str.print(reader.getTerminal());
        }
    }

    @Override
    public void closeClient() {
        try {
            terminalRunner.close();
        } catch (IOException e) {
            log.warn("failed to close terminal", e);
        }
    }

    @Override
    public void closeServer() {
        System.exit(0);
    }
}
